# -*-coding:utf-8 -*-

import struct


def typeList():
    return {
        'D0CF11E0': 'DOC',
        '504B0304': 'DOCX',
        '68746D6C3E': 'HTML',
        '3C21444F4354': 'HTML3',
        '3C48544D4C3E': 'HTML2',
        '3C68746D6C3E': 'HTML1',
        '255044462D312E': 'PDF',

        # '3C3F786D6C': 'XML',
        # '3C3F78':'XML1',
        # 'FFFE3C0052004F004F0054005300540055004200':'XML2'
    }

    # 字节码转16进制字符串


def bytes2hex(bytes):
    num = len(bytes)
    hexstr = u""
    for i in range(num):
        t = u"%x" % bytes[i]
        if len(t) % 2:
            hexstr += u"0"
        hexstr += t
    return hexstr.upper()

# 获取文件类型


def filetype(filename):
    # 验证是否能通过路径读取文件的内容
    # print('>>>>>>>',filename)
    # binfile = open(filename, 'r').read()
    # print('<<<<<<<',binfile)
    binfile = open(filename, 'rb')  # 必需二制字读取
    tl = typeList()
    ftype = 'txt'  # 默认文件格式是 txt
    for hcode in tl.keys():
        numOfBytes = len(hcode) / 2  # 需要读多少字节
        binfile.seek(0)  # 每次读取都要回到文件头，不然会一直往后读取
        hbytes = struct.unpack_from("B"*numOfBytes, binfile.read(numOfBytes))  # 一个 "B"表示一个字节
        f_hcode = bytes2hex(hbytes)
        if f_hcode == hcode:
            ftype = tl[hcode]
            break
    binfile.close()
    # print(ftype)  # 验证文件类型是否能匹配
    return ftype


# if __name__ == '__main__':
#     print filetype('E:\programs\\hello.doc')
